package pkg

import (
	"advertising/internal/app/grpc/client"
	"advertising/internal/app/grpc/protoc/system_admin"
	"context"
	"fmt"
	"net/url"
	"regexp"
	"strconv"
	"strings"

	"192.168.1.75/go-pkg/logx"
	"github.com/PuerkitoBio/goquery"
)

// 保留小数位数
func Decimal(val float64, len int) float64 {
	valStr := fmt.Sprintf("%."+strconv.Itoa(len)+"f", val)
	floatVal, _ := strconv.ParseFloat(valStr, 64)
	return floatVal
}

// 富文本框中的图片确认
func HandlerHtml(str string) string {
	if str == "" {
		return str
	}
	SystemAdminClient, clientErr := client.GetSystemAdminClient()
	if clientErr != nil {
		return str
	}
	reader := strings.NewReader(str)
	doc, err := goquery.NewDocumentFromReader(reader)
	if err == nil {
		doc.Find("img").Each(func(_ int, s *goquery.Selection) {
			src, _ := s.Attr("src")
			URL, _ := url.Parse(src)
			match, matchErr := regexp.MatchString("^(/file/advertising/).*(/temp/).*$", URL.Path)
			if matchErr == nil && match {
				// 文件确认
				var req system_admin.ConfirmFileReq
				req.FileUrl = URL.Path
				res, err1 := SystemAdminClient.ConfirmFile(context.Background(), &req)
				if err1 != nil && res.Code != 0 {
					logx.Error(context.Background(), "schedule confirm file error", logx.Any("res", res), logx.Any("err", err.Error()))
					return
				}
				ImagePath := URL.Scheme + "://" + URL.Host + res.FileUrl
				s.SetAttr("src", ImagePath) // 修改标签的内容
			}
		})
	}
	newGoods, _ := goquery.OuterHtml(doc.Selection)
	returnHtml := strings.TrimSuffix(strings.TrimPrefix(newGoods, "<html><head></head><body>"), "</body></html>")
	return returnHtml
}
